$(function(){  
    // variables
    var dropArea = document.getElementById('dropArea');
    var canvas = document.querySelector('canvas');
    var context = canvas.getContext('2d');
    var count = document.getElementById('count');
    var destinationUrl = document.getElementById('url');
    var result = document.getElementById('result');
    var list = [];
    var totalSize = 0;
    var totalProgress = 0;
    var typesFichiers = ["gif", "jpg", "png", "bmp", "jpeg", "jpe"];  // Contient la liste des fichiers acceptes

    // main initialization
    

    // init handlers
    function initHandlers() {
        dropArea.addEventListener('drop', handleDrop, false);
        dropArea.addEventListener('dragover', handleDragOver, false);
    }

    // draw progress
    function drawProgress(progress) {
        context.clearRect(0, 0, canvas.width, canvas.height); // clear context

        context.beginPath();
        context.strokeStyle = '#4B9500';
        context.fillStyle = '#4B9500';
        context.fillRect(0, 0, progress * 180, 20);
        context.closePath();

        // draw progress (as text)
        context.font = '16px Verdana';
        context.fillStyle = '#000';
        context.fillText('Progress: ' + Math.floor(progress*100) + '%', 30, 15);
    }

    // drag over
    function handleDragOver(event) {
        event.stopPropagation();
        event.preventDefault();

        dropArea.className = 'hover';
    }

    // drag drop
    function handleDrop(event) {
        event.stopPropagation();
        event.preventDefault();

        processFiles(event.dataTransfer.files);
    }

    // process bunch of files
    function processFiles(filelist) {
        if (!filelist || !filelist.length || list.length) return;

        totalSize = 0;
        totalProgress = 0;
        result.textContent = '';

        for (var i = 0; i < filelist.length && i < 1000; i++) {
            list.push(filelist[i]);
            totalSize += filelist[i].size;
        }
        uploadNext();
    }

    // on complete - start next file
    function handleComplete(size) {
        totalProgress += size;
        drawProgress(totalProgress / totalSize);
        uploadNext();
    }

    // update progress
    function handleProgress(event) {
        var progress = totalProgress + event.loaded;
        drawProgress(progress / totalSize);
    }

    // upload file
    function uploadFile(file, status) {

        // prepare XMLHttpRequest
        var xhr = new XMLHttpRequest();
        xhr.open('POST', destinationUrl.value);
        xhr.onload = function() {
            result.innerHTML += this.responseText;
            handleComplete(file.size);
        };
        xhr.onerror = function() {
            result.textContent = this.responseText;
            handleComplete(file.size);
        };
        xhr.upload.onprogress = function(event) {
            handleProgress(event);
        }
        xhr.upload.onloadstart = function(event) {
        }

        // prepare FormData
        var formData = new FormData();  
        formData.append('unePhoto', file); // myfile
        xhr.send(formData);
        
    }
    
    // Fonction verifiant si le type du fichier est accepte
    function typeFichier(nomFichier){

            // Verifier si le nom est correct
            if( nomFichier.length == 0 ) return false; 

            // Recuperer l'extention
            var positionPoint = nomFichier.lastIndexOf("."); 
            if( positionPoint == -1 ) return false; 
            var uneExtention = nomFichier.substr(positionPoint+1,nomFichier.length); 

            // Verifier si l'extention est acceptee
            for (var i = 0; i < typesFichiers.length; i++) {
                if (typesFichiers[i] == uneExtention)
                    return true;
            }

            // Renvoyer valeur par defaut
            return false;

    }

    // upload next file
    function uploadNext() {
        if (list.length) {
            count.textContent = list.length - 1;
            dropArea.className = 'uploading';

            var nextFile = list.shift();
            
            // Verifier si l'extention du fichier est correcte
            if(typeFichier(nextFile.name) == true){

                    // Verifier si la taille du fichier est admise
                    if (nextFile.size >= 4194304) { // 4mb
                            result.innerHTML += '<div class="f">Fichier trop lourd.</div>';
                            handleComplete(nextFile.size);
                    } else {
                            // Uploader la photo
                            uploadFile(nextFile, status);
                    }

            }
            else {
                    result.innerHTML += '<div class="f">Type de fichier non supporte</div>';
                    handleComplete(nextFile.size);
            }

        } else {
            dropArea.className = '';
        }
    }

    initHandlers();
});